$(document).ready(function(){
	$(".error").each(function(){
		if($(this).text() != "")
		{
			$(this).closest(".form-group").addClass("has-error")
		}
	})	
})
function addDatePicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                clearBtn:1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addDateRangePicker(selector){
	$(selector).datepicker({                
            });
};

function addDateTimePicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addMonthPicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 3,
                minView:3,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addTimePicker(selector){
	$(selector).datetimepicker({
                autoclose: 1,
                startView: 1,
                format:"hh:ii",
                pickerPosition:'bottom-left'
            });
};

function initialTableSort(tableId,sortColumnId){
	var sortColumns = $(sortColumnId).val();
	var sortColumn = sortColumns.split(",");
	for(var i = 0;i<sortColumn.length;i++){
		var sort = sortColumn[i].split(" ");
		var sortType = "asc";
		if(sort.length > 1){
			sortType = sort[1];
		}
		var columnName = sort[0];
		var obj = $(tableId).find('tr th[data-name="' + columnName + '"]')
		obj.attr('sort-type',sortType)
		
			obj.removeClass("sorting")
			obj.removeClass("sorting_asc")
			obj.removeClass("sorting_desc")
			obj.addClass("sorting_"+sortType)
		
		
	}
}
function addCustomPaginator(selector,formId,sortColumnId,pageNumberId,currentPage, totalPages){
	var options = {
		bootstrapMajorVersion: 3,
		alignment: "right",
	    currentPage: currentPage,
	    numberOfPages: 5,
	    totalPages: totalPages,	    
	    useBootstrapTooltip: true,//是否使用 bootstrap 自带的提示框
	    itemContainerClass: function (type, page, currentpage) {  //每项的类名
            //alert(type + "  " + page + "  " + currentpage)
            var classname = "p_item ";

            switch (type) {
                case "first":
                    classname += "p_first";
                    break;
                case "last":
                    classname += "p_last";
                    break;
                case "prev":
                    classname += "p_prev";
                    break;
                case "next":
                    classname += "p_next";
                    break;
                case "page":
                    classname += "p_page";
                    break;
            }

            if (page == currentpage) {
                classname += " active "
            }

            return classname;
        },
        itemTexts: function (type, page, current) {  //
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上页";
                case "next":
                    return "下页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "上页";
                case "next": return "下页";
                case "last": return "末页";
                case "page": return page === current ? "当前页数 " + page : "前往第 " + page + " 页"
            }
        },
	    onPageClicked: function(e,originalEvent,type,page){
	    	e.stopImmediatePropagation();            	
	    	var currentTarget = $(e.currentTarget);
	        var currentPage = currentTarget.bootstrapPaginator("getPages").current;
	        
	        if (currentPage != page){
	        	changeCustomPageNumber(formId,pageNumberId,page);
	    	}	    	
	    	return;
	    }
    }
    
    $(selector).bootstrapPaginator(options);
}

function changeCustomPageNumber(formId,pageNumberId,pageNumber)
{
	$(pageNumberId).val(pageNumber)
	$(formId).submit()
}

function changeSort(formId,tableId,sortColumnId,pageNumberId){
	$(tableId).find('tr th').each(function(){
		$(this).click(function(){
			var columnName = $(this).attr("data-name");
			if(typeof(columnName) == "undefined" || columnName == ''){
				return;
			}
			var sortType = $(this).attr("sort-type");
			if(typeof(sortType) == "undefined" || sortType == '' || sortType == 'desc'){
				sortType = "asc";
			}else{
				sortType = "desc";
			}
			$(sortColumnId).val(columnName + " " + sortType);
			$(pageNumberId).val("1");
			$(formId).submit();
			$(this).attr("sort-type",sortType);
		})
	})
}

function formvalidation(formId,option){
	var defaultOption = {
		errorElement: "em",
		errorPlacement: function ( error, element ) {
			// Add the `help-block` class to the error element
			error.addClass( "help-block" );

			if ( element.prop( "type" ) === "checkbox" ) {
				error.insertAfter( element.parent( "label" ) );
			} else {
				error.insertAfter( element );
			}
		},
		highlight: function ( e, errorClass, validClass ) {
			//$( e ).parents( ".col-md-6" ).addClass( "has-error" ).removeClass( "has-success" );
			$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
		},
		success: function (e) {
			$(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
			$( e ).parents( ".col-md-6" ).addClass( "has-success" ).removeClass( "has-error" );
			
		},
		unhighlight: function (e, errorClass, validClass) {
			$( e ).parents( ".col-md-6" ).addClass( "has-success" ).removeClass( "has-error" );
			$(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
			
		}
	};
	var actualOption = $.extend({},defaultOption,option||{});
	$(formId).validate(actualOption);
}

function loginformvalidation(formId,option){
	var defaultOption = {
		errorElement: "em",
		errorPlacement: function ( error, element ) {
			// Add the `help-block` class to the error element
			error.addClass( "help-block" );			
		},
		highlight: function ( e, errorClass, validClass ) {
			//$( e ).parents( ".col-md-6" ).addClass( "has-error" ).removeClass( "has-success" );
			$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
		},
		success: function (e) {
			$(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
			$( e ).parents( ".col-md-12" ).addClass( "has-success" ).removeClass( "has-error" );
			
		},
		unhighlight: function (e, errorClass, validClass) {
			$( e ).parents( ".col-md-12" ).addClass( "has-success" ).removeClass( "has-error" );
			$(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
		}
	};
	var actualOption = $.extend({},defaultOption,option||{});
	$(formId).validate(actualOption);
}

function deleteOne(button,url){
	$(button).click(function(){
		var id = $(this).attr("id").split("-")[1];
		if(confirm("确定进行删除操作吗？与其相关联的记录也会被清除")){
			$.ajax({
				url:url,
				data:{
					id: id
				},
				type : 'post',
				dataType : 'text',
				success : function(data){
					if(data == "success"){
						setTimeout("location.reload()",100);
					}
				},
				error : function(jqXHR, textStatus, errorThrown){
					alert(jqXHR.responseText + "|" + errorThrown)
				}
			})
		}
		
	})
}

function addPopup(button,url,popupTitle,width,height){
	width = width || 500;
	height = height || 700;
	$(button).click(function(){
		
		var diag = new top.Dialog();
		 diag.Drag=true;
		 diag.Title =popupTitle;
		 diag.URL = url;
		 diag.Width = width;
		 diag.Height = height;
		 diag.CancelEvent = function(){ //关闭事件
			 	var afterupdate = diag.innerFrame.contentWindow.document.getElementById('afterupdate');
		 		if(afterupdate)
	 			{
		 			if(afterupdate.style.display == 'none'){
						setTimeout("location.reload()",100);
					}
	 			}					
				diag.close();
			 };
		 diag.show();
	})
}

function editPopup(button,url,popupTitle,width,height){
	width = width || 500;
	height = height || 700;
	$(button).click(function(){
		var id = $(this).attr("id").split("-")[1]
		var diag = new top.Dialog();
		 diag.Drag=true;
		 diag.Title =popupTitle;
		 diag.URL = url+"?id="+id;
		 diag.Width = width;
		 diag.Height = height;
		 diag.CancelEvent = function(){ //关闭事件
			 	var afterupdate = diag.innerFrame.contentWindow.document.getElementById('afterupdate');
		 		if(afterupdate)
	 			{
		 			if(afterupdate.style.display == 'none'){
						setTimeout("location.reload()",100);
					}
	 			}					
				diag.close();
			 };
		 diag.show();
	})
}

function checkAllRecord(checkAllId, otherCheckClass){
	$(checkAllId).click(function(){
		$(otherCheckClass).prop("checked",$(checkAllId).prop("checked"));
	})
	
}

function deleteAll(deleteButton,url,checkboxName,message){
	$(deleteButton).click(function(){
		if(confirm("确定进行删除操作吗？与其相关联的记录也会被清除")){
			var checked=[];
			$('input[name="'+checkboxName+'"]:checked').each(function(){
				checked.push($(this).val());
			})
			if(checked.length == 0){
				alert(message);
				return;
			}
			$.ajax({
				url:url,
				data:{
					ids: checked.join(",")
				},
				type : 'post',
				dataType : 'text',
				success : function(data){
					if(data == "success"){
			
						setTimeout("location.reload()",100);
					}
				}
			})
		}
	})
}

function secureSubmit(formId,submitButtonId){
	 $(submitButtonId).click(function(){
		 
		 $.ajax({
			 url:"/backend/encryption/generateKeypair?generateKeypair=true",
			 success:function(data){
				 var rsa = new RSAKey();
				 rsa.setPublic(data.n,data.e);
				 var aes = new AES(128);
				 
				 var encryptedAesKey = rsa.encrypt(aes.key);
				 
				 var serialize = $(formId).serialize();
				 var encrypt = aes.encrypt(serialize);
				 
				 $encryptedElement = $("<input />",{
				        type:'hidden',
				        name:"jCryption"
				      });
				 $encryptedElement.val(encryptedAesKey+"|"+encrypt);
				 
				 $.ajax({
					 url:"/backend/encryption/handshake",
					 data:{
						 key:encryptedAesKey
					 },
					 success:function(data){
						 if(aes.key == aes.decrypt(data.challenge)){
							 $(formId).find(":input").attr("disabled",true).end().append($encryptedElement).submit();
						 }else{
							 if(confirm("Authentication with Server failed, are you sure you want to submit this form unencrypted?"))
							{
								 $(formId).submit();
							}
						 }						 
					 },
					 error:function(){
						 confirm("Authentication with Server failed, are you sure you want to submit this form unencrypted?",function(){
							 $(formId).submit();
						 })
					 }					 
				 })
				 
				
			 }
		 })
	 })
}